import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutterhello/api/api.dart';
import 'package:flutterhello/controller/Controller.dart';
import 'package:flutterhello/util/host_util.dart';
import 'package:flutterhello/widgets/loading_dialog.dart';
import 'package:flutterhello/widgets/my_toast.dart';
import 'package:flutterhello/widgets/tips_card.dart';
import 'package:get/get.dart' as MyGet;
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:dio/dio.dart';

import '../../../my_app.dart';

class AddTeamUserPage extends StatefulWidget {
  @override
  _AddTeamUserPageState createState() => _AddTeamUserPageState();
}

class _AddTeamUserPageState extends State<AddTeamUserPage> {
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  List<Asset> images = [];
  String content = "";
  String title = "";
  String _error;
  var choseTeam = null;

  Future<void> loadAssets() async {
    List<Asset> resultList;
    String error;

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 9,
        enableCamera: true,
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      images = images + resultList;
      if (error == null) _error = 'No Error Dectected';
      print(_error);
    });
  }

  Widget buildGridView() {
    if (images.length == 0)
      return Padding(
        padding: EdgeInsets.all(10),
        child: GridView.count(
            crossAxisCount: 3,
            children: List.generate(1, (index) {
              return Container(
                height: 120,
                width: 120,
                decoration: BoxDecoration(
                  border: Border(
                      left: BorderSide(width: 1, color: Colors.black26),
                      right: BorderSide(width: 1, color: Colors.black26),
                      bottom: BorderSide(width: 1, color: Colors.black26),
                      top: BorderSide(width: 1, color: Colors.black26)),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: IconButton(
                  icon: Icon(Icons.add),
                  onPressed: loadAssets,
                ),
              );
            })),
      );
    else
      return Padding(
        padding: EdgeInsets.all(10),
        child: GridView.count(
          crossAxisCount: 3,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          children: List.generate(images.length, (index) {
            Asset asset = images[index];
            return AssetThumb(
              asset: asset,
              width: 300,
              height: 300,
            );
          }),
        ),
      );
  }

  Widget buildGridView1() {
    if (images.length == 0)
      return GridView.count(
          crossAxisCount: 3,
          children: List.generate(1, (index) {
            print("fuck");
            return Container(
              height: 120,
              width: 120,
              decoration: BoxDecoration(
                border: Border(
                    left: BorderSide(width: 1, color: Colors.black26),
                    right: BorderSide(width: 1, color: Colors.black26),
                    bottom: BorderSide(width: 1, color: Colors.black26),
                    top: BorderSide(width: 1, color: Colors.black26)),
                borderRadius: BorderRadius.circular(5),
              ),
              child: IconButton(
                icon: Icon(Icons.add),
                onPressed: loadAssets,
              ),
            );
          }));
    else
      return GridView.count(
        crossAxisCount: 3,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        children: List.generate(images.length + 1, (index) {
          if (index < images.length) {
            Asset asset = images[index];
            return Container(
              width: 300,
              height: 300,
              child: Stack(
                children: [
                  Align(
                    alignment: Alignment(0, 0),
                    child: AssetThumb(
                      asset: asset,
                      width: 300,
                      height: 300,
                    ),
                  ),
                  Align(
                    alignment: Alignment(0.9, -0.9),
                    child: GestureDetector(
                      child: Icon(
                        const IconData(0xe600, fontFamily: "alIcons"),
                        size: 15,
                        color: Colors.blueGrey,
                      ),
                      onTap: () {
                        setState(() {
                          this.images.removeAt(index);
                        });
                      },
                    ),
                  )
                ],
              ),
            );
          } else {
            return Container(
              height: 120,
              width: 120,
              decoration: BoxDecoration(
                border: Border(
                    left: BorderSide(width: 1, color: Colors.black26),
                    right: BorderSide(width: 1, color: Colors.black26),
                    bottom: BorderSide(width: 1, color: Colors.black26),
                    top: BorderSide(width: 1, color: Colors.black26)),
                borderRadius: BorderRadius.circular(5),
              ),
              child: IconButton(
                icon: Icon(Icons.add),
                onPressed: loadAssets,
              ),
            );
          }
        }),
      );
  }

  @override
  Widget build(BuildContext _context) {
    final controller = MyGet.Get.put(Controller());
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          title: Text('发布招募'),
          centerTitle: true,
        ),
        preferredSize: Size.fromHeight(50),
      ),
      body: Container(
        margin: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  TextField(
                    cursorColor: Colors.black87,
                    cursorWidth: 0.5,
                    maxLines: 1,
                    style: TextStyle(color: Colors.black54, fontSize: 16),
                    scrollPadding: EdgeInsets.all(0),
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(0),
                      hintText: '标题',
                      hintStyle: TextStyle(fontSize: 14, color: Colors.black38),
                      border: InputBorder.none,
                    ),
                    onChanged: (value) {
                      this.title = value;
                    },
                  ),
                  Container(
                    height: 100,
                    width: double.infinity,
                    child: TextFormField(
                      cursorColor: Colors.black87,
                      cursorWidth: 0.5,
                      maxLines: 7,
                      style: TextStyle(color: Colors.black54, fontSize: 16),
                      scrollPadding: EdgeInsets.all(0),
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(0),
                          hintText: '输入招募说明',
                          hintStyle:
                              TextStyle(fontSize: 14, color: Colors.black26),
                          border: InputBorder.none),
                      onChanged: (val) {
                        this.content = val;
                      },
                    ),
                  ),
                  GestureDetector(
                    child: this.choseTeam == null
                        ? Container(
                            width: double.infinity,
                            height: 50,
                            decoration: BoxDecoration(
                              border: Border(
                                  top: BorderSide(color: Colors.black26),
                                  bottom: BorderSide(color: Colors.black26)),
                            ),
                            child: Row(
                              children: [
                                Text(
                                  '选择团队',
                                  style: TextStyle(color: Colors.black45),
                                ),
                              ],
                            ),
                          )
                        : TipsCard(
                            favicon:
                                HostUtil.getHost() + this.choseTeam['favicon'],
                            name: this.choseTeam['groupname'],
                          ),
                    onTap: () {
                      showModalBottomSheet<void>(
                        context: context,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            topRight: Radius.circular(20),
                          ),
                        ),
                        builder: (BuildContext context) {
                          return EasyRefresh.custom(
                            slivers: <Widget>[
                              SliverToBoxAdapter(
                                child: SizedBox(
                                  height: 20,
                                ),
                              ),
                              SliverList(
                                delegate: SliverChildBuilderDelegate(
                                  (context, index) {
                                    return Padding(
                                      padding: EdgeInsets.only(
                                        left: 20,
                                        right: 20,
                                      ),
                                      child: Column(
                                        children: [
                                          SizedBox(
                                            height: 10,
                                          ),
                                          GestureDetector(
                                            child: TipsCard(
                                              favicon: HostUtil.getHost() +
                                                  controller
                                                          .myCreateGroup[index]
                                                      ['favicon'],
                                              name: controller
                                                      .myCreateGroup[index]
                                                  ['groupname'],
                                            ),
                                            onTap: () {
                                              this.choseTeam = controller
                                                  .myCreateGroup[index];
                                              Navigator.of(context).pop();
                                              setState(() {});
                                            },
                                          ),
                                        ],
                                      ),
                                    );
                                  },
                                  childCount: controller.myCreateGroup.length,
                                ),
                              )
                            ],
                          );
                        },
                      );
                    },
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(top: 10),
                      child: buildGridView1(),
                    ),
                  ),
                  Align(
                    alignment: Alignment(0.8, 0),
                    child: GestureDetector(
                      child: Container(
                        height: 50,
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: Colors.blueGrey,
                          borderRadius: BorderRadius.all(Radius.circular(5)),
                        ),
                        child: Center(
                          child: Text(
                            '提 交',
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                        ),
                      ),
                      onTap: () async {
                        var result = await showDialog(
                            context: context,
                            builder: (context) {
                              return AlertDialog(
                                title: Text('提示'),
                                content: Text('确认上传吗？'),
                                actions: <Widget>[
                                  TextButton(
                                    child: Text('取消'),
                                    onPressed: () {
                                      Navigator.of(context).pop('cancel');
                                    },
                                  ),
                                  TextButton(
                                    child: Text('确认'),
                                    onPressed: () {
                                      Navigator.of(context).pop('ok');
                                      submit(
                                          this.images,
                                          this.title,
                                          this.content,
                                          this.choseTeam,
                                          _context);
                                    },
                                  ),
                                ],
                              );
                            });
                        print('$result');
                      },
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

void submit(images, title, content, group, context) async {
  if (title != "" && images.length != 0 && group != null) {
    try {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new LoadingDialog(
            text: "上传中…",
          );
        },
      );
      FormData formData = new FormData.fromMap({});
      for (int i = 0; i < images.length; i++) {
        ByteData byteData = await images[i].getByteData();
        List<int> imageData = byteData.buffer.asUint8List();
        MultipartFile multipartFile = MultipartFile.fromBytes(
          imageData,
          filename: images[i].name,
        );
        formData.files.addAll([
          MapEntry("file", multipartFile),
        ]);
      }
      var res = await Api.uploadImg(formData);
      if (res['code'] == 1000) {
        var res2 = await Api.createRecruit({
          "groupID": group['id'],
          "title": title,
          "content": content,
          "images": res['data']
        });
        if (res2['code'] == 1000) {
          Navigator.of(context).pop();
          MyTost.showTost(res2['message']);
          MyGet.Get.offAll(MyApp());
        }
      } else {
        MyTost.showTost('上传失败');
        Navigator.of(context).pop();
      }
    } catch (err) {
      Navigator.of(context).pop();
    }
  } else {
    MyTost.showTost('标题、团队、图片必填');
  }
}
